home *** CD-ROM | disk | FTP | other *** search
- Path: news.gate.net!pslfl2-22
- From: bhutto@gate.net (William Hutto)
- Newsgroups: comp.lang.c
- Subject: Re: quick decision: is n a power of 2?
- Date: 21 Jan 1996 20:48:21 GMT
- Organization: CyberGate, Inc.
- Message-ID: <4du8ql$1vdq@news.gate.net>
- References: <Pine.OSF.3.91.960119114608.18779E-100000@io.UWinnipeg.ca> <4dpian$gij@oxy.rust.net> <9601201820.AA01752@dxmint.cern.ch> <4dtqpq$sl2@oxy.rust.net>
- NNTP-Posting-Host: pslfl2-22.gate.net
- X-Newsreader: News Xpress Version 1.0 Beta #4
-
- In article <4dtqpq$sl2@oxy.rust.net>, ebennett@rust.net spake:
- ;Dan Pop <danpop@mail.cern.ch> wrote:
- ;
- ;>ebennett@rust.net writes:
- ;
- ;>>Given some number, there is a neat trick to generate a mask which will
- ;>>have exactly one bit set in it. The bit set will be the least
- ;>>significant non-zero bit in the original number:
- ;>>
- ;>> mask = ~number & number;
- ;>>
- ;>>Now, if number contained a single non-zero bit (and is therefore a
- ;>>power of 2), mask will be equal to number. Therefore:
- ;>>
- ;>> if (number == (~number & number))
- ;>> {
- ;>> /* number is a power of 2 */
- ;>> }
- ;>>
- ;>>Try it, you'll like it!
- ;
- ;>I don't think so. ~number & number will _always_ give 0. -number & number
- ;>will actually work, except for the case when number == 0. That is,
- ;>assuming a two's complement implementation. On a one's complement or
- ;>sign-magnitude implementation it won't work at all.
- ;
- ;>Yet another guy who makes a fool of himself because he's too lazy to
- ;>test his solution before posting.
- ;
- ;>Dan
- ;
- ;You are correct in that I made a typo in my message. ~ should have
- ;been -. There are also some limitations which did not occur to me,
- ;which you have rightly pointed out.
- ;
- ;I agree with the problem with 0, and that is easily checked for.
- ;Where would you run into a one's complement or sign-magnitude
- ;implementation?
- ;
- ;However, I do not feel that I made a fool of myself. Most of us are
- ;not perfect as you apparently are. The rest of us make mistakes, and
- ;learn from them. That does not make us fools.
- ;
- ;Earl
-
- You could always change the -number to (~number+1).
-
- Bill
-
- William Hutto
- bhutto@gate.net
- N4YMN
-
- "Whatcha got on?...Your mind?"
-